package com.teamventure.app;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.teamventure.app.util.Connect;
import com.teamventure.app.util.UserData;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private ListView lv;
	
	/*
	 * First activity that comes up when MobileRunner is started
	 */
	private static MainActivity mainActivity;
	
	/**
	 * Returns the main activity
	 * 
	 * @return The main activity
	 */
	public static MainActivity getInstance(){
		return mainActivity;
	}
	
	@Override
	public void onStart() {
		super.onStart();
		if(UserData.getUserData().getUsername() != ""
			&& UserData.getUserData().getPassword() != "") {
			this.displayDeals();
		}
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);
		
		File prefFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+UserData.PREFS_LOC);
		if(!prefFile.isFile()) {
			try{
				prefFile.createNewFile();
			} catch(IOException e) {
				//TODO Do something with the caught exception
			}
		}
		
		Scanner scanPrefs = null;
		try{
			scanPrefs = new Scanner(new FileInputStream(prefFile));
		} catch(IOException e) {
			//TODO Do something with the caught exception
		}
		
		//If scanPrefs is not null, check to see if it contains connection information
		if(scanPrefs != null) {
			if(scanPrefs.hasNextLine()) {
				String username = scanPrefs.nextLine();
				if(username.length() > 0) {
					UserData.getUserData().setUsername(username);
				}
				if(scanPrefs.hasNextLine()) {
					String password = scanPrefs.nextLine();
					if(password.length() > 0) {
						UserData.getUserData().setPassword(password);
					}
				}
			}
		}
		
		//If the prefs file didn't work, go to the login screen
		if(UserData.getUserData().getUsername() == "" 
			|| UserData.getUserData().getPassword() == "") {
			startActivity(new Intent(MainActivity.this, LoginActivity.class));
		}
	}
	
	private void displayDeals() {
		Deal[] deals = {};
		Connect c = UserData.getUserData().getConnection();
		
		HashMap<String,String> params = new HashMap<String,String>();
		params.put("username", UserData.getUserData().getUsername());
		params.put("password", UserData.getUserData().getPassword());
		
		String response = c.sendRequest("getCustID", params);
		
		JSONTokener toke = new JSONTokener(response);
		JSONArray arr = null;
		JSONObject obj = null;
		String custID = "";
		try {
			arr = new JSONArray(toke);
			obj = arr.getJSONObject(0);
			custID = (String)obj.get("idcust_acct");
		} catch(JSONException e) {
			
		}
		
		params = new HashMap<String,String>();
		params.put("customer_id", custID);
		response = c.sendRequest("listDeals", params);
		
		toke = new JSONTokener(response);
		try {
			arr = new JSONArray(toke);
			deals = new Deal[arr.length()];
			for(int i=0; i<arr.length(); i++) {
				obj = arr.getJSONObject(i);
				Deal d = new Deal((String)obj.get("name"),(String)obj.get("message"));
				deals[i] = d;
			}
		} catch(JSONException e) {
			
		}
		
		lv.setAdapter(new DealAdapter(this, R.layout.deal, deals));
		
		registerForContextMenu(lv);
		
		final Intent intent = new Intent().setClass(this, FeedbackActivity.class);
		
	}
	
	private class Deal {
		private String busName = "";
		private String desc = "";
		public Deal(String busName, String desc) {
			this.busName = busName;
			this.desc = desc;
		}
		public String getBusName() {
			return this.busName;
		}
		public String getDesc() {
			return this.desc;
		}
	}
	
	private class DealAdapter extends ArrayAdapter<Deal> {
		private Deal[] deals;
		public DealAdapter(Context context, int textViewResourceId, Deal[] objects) {
			super(context, textViewResourceId, objects);
			this.deals = objects;
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if(v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.deal, null);
			}
			Deal d;
			if(position>=0 && position<deals.length) {
				d = this.deals[position];
				TextView tt = (TextView)v.findViewById(R.id.toptext);
				TextView bt = (TextView)v.findViewById(R.id.bottomtext);
				if(tt != null) {
					tt.setText(d.getBusName());
				}
				if(bt != null) {
					bt.setText(d.getDesc());
				}
			}
			return v;
		}
	}
}
